package com.agileai.miscdp.hotweb.ui.celleditors.dialog;

import java.util.ArrayList;
import java.util.List;

import net.sf.swtaddons.autocomplete.combo.AutocompleteComboInput;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.ResFileValueProvider;
import com.agileai.miscdp.hotweb.ui.dialogs.FieldSelectDialog;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;
/**
 * 组合编辑器提示框
 */
public class ResourceFileProviderDialog extends Dialog {
	private String code = null;
	
	private Text codeText;
	private Combo relTableCombo;
	private PageFormField pageParameter = null;
	
	private String projectName = null;
	private Text primaryKeyText;
	private Text bizIdFieldText;
	private Text resIdFieldText;
	private BaseModelEditor modelEditor;
	
	public ResourceFileProviderDialog(BaseModelEditor modelEditor,Shell parentShell,String projectName) {
		super(parentShell);
		this.projectName = projectName;
		this.modelEditor = modelEditor;
	}
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		container.setLayout(gridLayout);

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setText("字段编码");

		codeText = new Text(container, SWT.BORDER);
		codeText.setEditable(false);
		codeText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				code = codeText.getText();
				pageParameter.setCode(code);
			}
		});
		codeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		
		final Label label = new Label(container, SWT.NONE);
		label.setText("附件关联表");

		relTableCombo = new Combo(container, SWT.NONE);
		relTableCombo.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				String relTable = relTableCombo.getText();
				if (!StringUtil.isNullOrEmpty(relTable) && relTable.length() > 3){
					DBManager dbManager = DBManager.getInstance(projectName);
					String[] fields = MiscdpUtil.getColNames(dbManager, relTable);
					String[] primaryKeys = dbManager.getPrimaryKeys(relTable);
					List<String> fieldList = new ArrayList<String>();
					ListUtil.addArrayToList(fieldList, fields);
					
					if (primaryKeys != null && primaryKeys.length > -1){
						primaryKeyText.setText(primaryKeys[0]);
					}
					if (fieldList.contains(ResFileValueProvider.BizIdField)){
						bizIdFieldText.setText(ResFileValueProvider.BizIdField);
					}
					if (fieldList.contains(ResFileValueProvider.ResIdField)){
						resIdFieldText.setText(ResFileValueProvider.ResIdField);
					}
				}
			}
		});
		relTableCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		new AutocompleteComboInput(relTableCombo);
		
		Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_3.setText("关联逻辑主键");
		
		primaryKeyText = new Text(container, SWT.BORDER);
		primaryKeyText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		primaryKeyText.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				openFieldSelectDialog(primaryKeyText);
			}
		});

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_2.setText("业务标识字段");
		
		bizIdFieldText = new Text(container, SWT.BORDER);
		bizIdFieldText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		bizIdFieldText.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				openFieldSelectDialog(bizIdFieldText);
			}
		});

		final Label label_2_1 = new Label(container, SWT.NONE);
		label_2_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		label_2_1.setText("附件标识字段");
		
		resIdFieldText = new Text(container, SWT.BORDER);
		resIdFieldText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		resIdFieldText.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				openFieldSelectDialog(resIdFieldText);
			}
		});
		
		this.initValues();
		return container;
	}
	
	@SuppressWarnings("unchecked")
	private void initValues(){
		codeText.setText("__ResouceList");
		List<String> tableList = DBManager.getInstance(projectName).getTables(null);
		relTableCombo.setItems(tableList.toArray(new String[0]));
		int tableCount = this.relTableCombo.getItemCount();
		
		String valueProvider = pageParameter.getValueProvider();
		if (!StringUtil.isNullOrEmpty(valueProvider)){
			try {
				JSONObject jsonObject = new JSONObject(valueProvider);
				String tableName = jsonObject.getString(ResFileValueProvider.TableNameKey);
				String primaryKeyField = jsonObject.getString(ResFileValueProvider.PrimaryKeyFieldKey);
				String bizIdField = jsonObject.getString(ResFileValueProvider.BizIdFieldKey);
				String resIdField = jsonObject.getString(ResFileValueProvider.ResIdFieldKey);
				
				if (tableName != null){
					for (int i=0;i < tableCount;i++){
						String tableNameTemp = this.relTableCombo.getItem(i).toLowerCase();
						if (tableName.toLowerCase().equals(tableNameTemp)){
							this.relTableCombo.select(i);
							break;
						}
					}
				}
				primaryKeyText.setText(primaryKeyField);
				bizIdFieldText.setText(bizIdField);
				resIdFieldText.setText(resIdField);
			} catch (Exception e) {
				MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
			}
		}
	}
	
	private void openFieldSelectDialog(Text targetText){
		String tableName = relTableCombo.getText();
		String[] fields = MiscdpUtil.getColNames(DBManager.getInstance(projectName), tableName);
		FieldSelectDialog dialog = new FieldSelectDialog(modelEditor,fields,targetText);
		dialog.open();
	}
	
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}
	
	@Override
	protected void okPressed() {
		if (StringUtil.isNullOrEmpty(relTableCombo.getText())){
    		String message = MiscdpUtil.getIniReader().getValue("ValueProviderDialog","RelTableNameNullMsg");
    		DialogUtil.showInfoMessage(message);
			return;
		}
		if (StringUtil.isNullOrEmpty(primaryKeyText.getText())){
    		String message = MiscdpUtil.getIniReader().getValue("ValueProviderDialog","PrimaryKeyFieldNullMsg");
    		DialogUtil.showInfoMessage(message);			
			return;
		}
		if (StringUtil.isNullOrEmpty(bizIdFieldText.getText())){
    		String message = MiscdpUtil.getIniReader().getValue("ValueProviderDialog","BizIdFieldNullMsg");
    		DialogUtil.showInfoMessage(message);
			return;
		}		
		if (StringUtil.isNullOrEmpty(resIdFieldText.getText())){
    		String message = MiscdpUtil.getIniReader().getValue("ValueProviderDialog","ResIdFieldNullMsg");
    		DialogUtil.showInfoMessage(message);
			return;
		}
		pageParameter.setDataType("other");
		pageParameter.setLabel(codeText.getText());
		pageParameter.setCode(codeText.getText());
		
		String tableName = relTableCombo.getText();
		String primaryKeyField = primaryKeyText.getText();
		String bizIdField = bizIdFieldText.getText();
		String resIdField = resIdFieldText.getText();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put(ResFileValueProvider.TableNameKey, tableName);
			jsonObject.put(ResFileValueProvider.PrimaryKeyFieldKey, primaryKeyField);
			jsonObject.put(ResFileValueProvider.BizIdFieldKey, bizIdField);
			jsonObject.put(ResFileValueProvider.ResIdFieldKey, resIdField);
			pageParameter.setValueProvider(jsonObject.toString());
		} catch (JSONException e) {
			MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(),e);
		}
		super.okPressed();
	}
	@Override
	protected Point getInitialSize() {
		return new Point(317, 261);
	}
	
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("内容选择框");
	}
	
	public String getCode() {
		return code;
	}
	
	public void setPageParameter(PageFormField pageParameter) {
		this.pageParameter = pageParameter;
		this.code = pageParameter.getCode();
	}
}